package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.GENDER;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.Manifest;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.ApplyTradeUnionActivity;
import com.luoxiang.socialandroid.activity.AuditActivity;
import com.luoxiang.socialandroid.activity.DetailsActivity;
import com.luoxiang.socialandroid.activity.FfActivity;
import com.luoxiang.socialandroid.activity.GreetActivity;
import com.luoxiang.socialandroid.activity.OperationsActivity;
import com.luoxiang.socialandroid.activity.RecommendActivity;
import com.luoxiang.socialandroid.activity.SetActivity;
import com.luoxiang.socialandroid.activity.TradeUnionDataActivity;
import com.luoxiang.socialandroid.activity.UserInfoActivity;
import com.luoxiang.socialandroid.activity.VipActivity;
import com.luoxiang.socialandroid.activity.VisitorActivity;
import com.luoxiang.socialandroid.activity.WalletActivity;
import com.luoxiang.socialandroid.app.MyAppliaction;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.Charge;
import com.luoxiang.socialandroid.bean.ChargeBaen;
import com.luoxiang.socialandroid.bean.DestroseBean;
import com.luoxiang.socialandroid.bean.GetUserData;
import com.luoxiang.socialandroid.bean.MineInfoBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.dialog.TipDialog;
import com.luoxiang.socialandroid.face.view.FaceBeautyActivity;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.lxj.xpopup.XPopup;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

/**
 * @Description 我的fragment
 * @systemUser Administrator
 * @Author LiangXin
 * @Date 08-20-2022 周六 10:59
 */
public class MineFragment extends LazyLoadFragment {
    private ImageView im_toset, image_mine_head, im_copy, im_bianji, im_kefu, imagePoint, imagePoint1;
    private TextView tx_mine_name, tx_mine_id, tx_mine_qm, tx_vip, tx_charge;
    private String token;
    private RelativeLayout r_ff, r_fk, r_op, r_kaitongvip, r_zhaohushezhi, r_yaoqingjiangli, r_zhenrenrenzheng, r_meiyancanshu, r_tonghuajiage, relativeMyUnion;
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private String url = "https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/";
    private RelativeLayout mine_wallet;
    private int host;
    private DestroseBean destroseBean;
    private int focusLogNum = 0;
    private int accessLogNum = 0;

    @Override
    protected int setContentView() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView() {
        r_ff = findViewById(R.id.r_ff);
        r_fk = findViewById(R.id.r_fk);
        r_op = findViewById(R.id.r_op);
        tx_charge = findViewById(R.id.tx_charge);
        r_kaitongvip = findViewById(R.id.r_kaitongvip);
        r_zhaohushezhi = findViewById(R.id.r_zhaohushezhi);
        r_yaoqingjiangli = findViewById(R.id.r_yaoqingjiangli);
        r_zhenrenrenzheng = findViewById(R.id.r_zhenrenrenzheng);
        r_tonghuajiage = findViewById(R.id.r_tonghuajiage);
        im_toset = findViewById(R.id.im_toset);
        image_mine_head = findViewById(R.id.image_mine_head);
        im_copy = findViewById(R.id.im_copy);
        im_bianji = findViewById(R.id.im_bianji);
        tx_mine_id = findViewById(R.id.tx_mine_id);
        tx_mine_name = findViewById(R.id.tx_mine_name);
        tx_mine_qm = findViewById(R.id.tx_mine_qm);
        tx_vip = findViewById(R.id.tx_vip);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        mine_wallet = findViewById(R.id.mine_wallet);
        r_meiyancanshu = findViewById(R.id.r_meiyancanshu);
        imagePoint = findViewById(R.id.imagePoint);
        imagePoint1 = findViewById(R.id.imagePoint2);
        relativeMyUnion = findViewById(R.id.relativeMyUnion);
        im_kefu = findViewById(R.id.im_kefu);
        UltimateBarX.addStatusBarTopPadding(findViewById(R.id.rl_root));
        Integer hostAudit = MmkvUtil.INSTANCE.decodeInt(HOSTAUDIT);
        if (hostAudit != null && hostAudit.equals(1)) {
            r_zhenrenrenzheng.setVisibility(View.VISIBLE);
            relativeMyUnion.setVisibility(View.VISIBLE);
        } else {
            r_zhenrenrenzheng.setVisibility(View.GONE);
            relativeMyUnion.setVisibility(View.GONE);
        }
        getUserInfo(token, EXTRA);
        im_toset.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), SetActivity.class);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        im_copy.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                ClipboardUtils.copyText(tx_mine_id.getText());
                ToastUtils.showShort(requireContext().getString(R.string.mi_copy_success));
            }

            @Override
            protected void onFastClick() {

            }
        });
        r_ff.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), FfActivity.class);
                intent.putExtra("focusLogNum",focusLogNum);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });

        r_fk.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), VisitorActivity.class);
                intent.putExtra("accessLogNum",accessLogNum);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        r_tonghuajiage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NetUtils2.getInstance().getApiService().getCharge(token, EXTRA)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<NumberBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(NumberBean numberBean) {
                                String data = numberBean.getData();
                                String decryptStr = null;
                                try {
                                    decryptStr = AESUtil.aesDecryptString(data, KEY);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                LogUtils.i("decryptStr44", decryptStr);
                                Gson gson = new Gson();
                                ChargeBaen bean = gson.fromJson(decryptStr, ChargeBaen.class);

                                ArrayList<String> strings = new ArrayList<>();
                                ArrayList<String> ids = new ArrayList<>();
                                if (bean != null) {
                                    if (bean.getData() != null && bean.getData().getCharges().size() != 0) {
                                        List<Charge> charges = bean.getData().getCharges();
                                        for (int i = 0; i < charges.size(); i++) {
                                            strings.add(charges.get(i).getCharge() + getString(R.string.mi_mifenzhong));
                                            ids.add(charges.get(i).getId() + "");
                                        }
                                        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
                                            @Override
                                            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                                                //返回的分别是三个级别的选中位置
                                                String tx = strings.get(options1);
                                                tx_charge.setText(tx);
                                                int channelIndex = options1;
                                                String channelNoName = strings.get(options1);
                                                tx_charge.setText(channelNoName + "");

                                                NetUtils2.getInstance().getApiService().setCharge(token, EXTRA, ids.get(options1))
                                                        .subscribeOn(Schedulers.io())
                                                        .observeOn(AndroidSchedulers.mainThread())
                                                        .subscribe(new Observer<NumberBean>() {
                                                            @Override
                                                            public void onSubscribe(Disposable d) {
                                                            }

                                                            @Override
                                                            public void onNext(NumberBean numberBean) {
                                                                String data = numberBean.getData();
                                                                String decryptStr = null;
                                                                try {
                                                                    decryptStr = AESUtil.aesDecryptString(data, KEY);
                                                                } catch (Exception e) {
                                                                    e.printStackTrace();
                                                                }
                                                                LogUtils.i("decryptStrprice", decryptStr);
                                                            }

                                                            @Override
                                                            public void onError(Throwable e) {
                                                            }

                                                            @Override
                                                            public void onComplete() {
                                                            }
                                                        });
                                            }
                                        }).build();

                                        pvOptions.setPicker(strings);
                                        pvOptions.show();

                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

            }
        });
        im_bianji.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                intent.putExtra("leixing", 1);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        r_op.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), OperationsActivity.class);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });

        r_kaitongvip.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), VipActivity.class);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        r_zhaohushezhi.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), GreetActivity.class);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        r_meiyancanshu.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                PermissionUtils.permission(Manifest.permission.CAMERA).callback(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(getActivity(), FaceBeautyActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onDenied() {
                        showToast(getString(R.string.mi_camera_video_quanxian));
                    }
                }).request();
            }

            @Override
            protected void onFastClick() {

            }
        });
        r_yaoqingjiangli.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), RecommendActivity.class);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        r_zhenrenrenzheng.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), AuditActivity.class);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        mine_wallet.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent(getActivity(), WalletActivity.class);
                startActivity(intent);
            }

            @Override
            protected void onFastClick() {

            }
        });
        relativeMyUnion.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (destroseBean == null || destroseBean.getData() == null || destroseBean.getData().getUser() == null) {
                    return;
                }
                switch (destroseBean.getData().getUser().getGuildCode()) {
                    case 0:
                        startActivity(new Intent(requireContext(), ApplyTradeUnionActivity.class));
                        break;
                    case 1:
                    case 2:
                        Toast.makeText(requireContext(), "工会正在审核中...", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        startActivity(new Intent(requireContext(), TradeUnionDataActivity.class));
                        break;
                }
            }

            @Override
            protected void onFastClick() {

            }
        });
        im_kefu.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE).withParam(RouterConstant.CHAT_KRY, new UserInfo("100000", "我的客服", "")).withContext(requireContext()).navigate();
            }

            @Override
            protected void onFastClick() {

            }
        });
    }

    @Override
    protected void lazyLoad() {

    }

    private void getUserInfo(String token, String extra) {
        getRequest();
        NetUtils.getInstance().getApiService().getMineUserInfo(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            LogUtils.i("decryptStrpq", decryptStr);
                            Gson gson = new Gson();
                            GetUserData bean = gson.fromJson(decryptStr, GetUserData.class);
                            if (bean.getData().getUser() != null) {
                                int charge = bean.getData().getUser().getCharge();
                                tx_charge.setText(charge + getString(R.string.mi_mifenzhong));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void initScreenRecorderBuild() {
        RxPermissions rxPermissions = new RxPermissions(getActivity());
        rxPermissions.request(
                Manifest.permission.CAMERA


        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {

                } else {
                    ToastUtils.showShort(R.string.mi_budakaiquanxianhuiyingxiangshiyong);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getRequest();
        getHomeUserInfo(token, EXTRA);
        getUserSimpleInfo(EXTRA, token);
    }

    private void getHomeUserInfo(String token, String extra) {
        NetUtils2.getInstance().getApiService().getHomeUserInfo(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            LogUtils.i("decryptStr0", decryptStr);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {

                            Gson gson = new Gson();
                            MineInfoBean bean = gson.fromJson(decryptStr, MineInfoBean.class);
                            Glide.with(MyAppliaction.getContext())
                                    .load(url + bean.getData().getUser().getIcon())
                                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
//                                    .transform(new GlideCircleWithBorder(this, 2, Color.parseColor("#ffffff")))
                                    .into(image_mine_head);
                            tx_mine_id.setText("" + bean.getData().getUser().getUserId());
                            tx_mine_name.setText(bean.getData().getUser().getName());
                            image_mine_head.setOnClickListener(new CustomClickListener() {
                                @Override
                                protected void onSingleClick() {
                                    Intent intent = new Intent(getActivity(), DetailsActivity.class);
                                    intent.putExtra("userid", bean.getData().getUser().getUserId());
                                    startActivity(intent);
                                }

                                @Override
                                protected void onFastClick() {

                                }
                            });
                            if (bean.getData().getUser().getPersionSign() != null) {
                                tx_mine_qm.setText(bean.getData().getUser().getPersionSign().toString());
                            }
                            host = bean.getData().getUser().getHost();
                            if (host == 1) {
                                r_zhaohushezhi.setVisibility(View.VISIBLE);
                                r_tonghuajiage.setVisibility(View.VISIBLE);
                            } else {
                                r_zhaohushezhi.setVisibility(View.GONE);
                                r_tonghuajiage.setVisibility(View.GONE);
                            }
                            if (bean.getData().getUser().getIdentity() != 0) {
                                tx_vip.setText(R.string.mi_wodehuiyuan);
                            }
                        } catch (Exception e) {
                            LogUtils.e("decryptStr0", e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.i("xx", e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getUserSimpleInfo(String extra, String token) {
        getRequest();
        NetUtils.getInstance().getApiService().getUserSimpleInfo(extra, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            LogUtils.i("decryptStrmineinfo", decryptStr);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Gson gson = new Gson();
                        destroseBean = gson.fromJson(decryptStr, DestroseBean.class);
                        if (destroseBean != null) {
                            if (destroseBean.getData() != null) {
                                if (destroseBean.getData().getUser() != null) {
                                    if (destroseBean.getData().getUser().getFocusLogNum() != null) {
                                        focusLogNum = destroseBean.getData().getUser().getFocusLogNum();
                                        if (destroseBean.getData().getUser().getFocusLogNum() > 0) {
                                            imagePoint.setVisibility(View.VISIBLE);
                                        } else {
                                            imagePoint.setVisibility(View.GONE);
                                        }
                                    }else{
                                        imagePoint.setVisibility(View.GONE);
                                    }

                                    if (destroseBean.getData().getUser().getAccessLogNum() != null) {
                                        accessLogNum = destroseBean.getData().getUser().getAccessLogNum();
                                        if (destroseBean.getData().getUser().getAccessLogNum() > 0) {
                                            imagePoint1.setVisibility(View.VISIBLE);
                                        } else {
                                            imagePoint1.setVisibility(View.GONE);
                                        }
                                    }else{
                                        imagePoint1.setVisibility(View.GONE);
                                    }

                                    if (destroseBean.getData().getUser().getHost() == 1) {
                                        r_zhenrenrenzheng.setVisibility(View.GONE);
                                    } else {
                                        Integer gender = MmkvUtil.INSTANCE.decodeInt(GENDER);
                                        if (gender != null && gender.equals(0)) {
                                            r_zhenrenrenzheng.setVisibility(View.VISIBLE);
                                        } else {
                                            r_zhenrenrenzheng.setVisibility(View.GONE);
                                        }
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }
}
